<template>
	<view class="page solid-top">
		<!-- 订单金额支付时间 start -->
		<view class="bg-white flex align-center justify-center flex-direction padding-top-64 padding-bottom-56">
			<view class="text-prices text-bold">
				<text class="text-price fu-fs32"></text>
				<text class="fu-fs64">{{orderInfo.payable_money}}</text>
			</view>
			<view class="text-666 margin-top-sm">
				{{i18n['支付剩余时间']}}：
				<text v-if='downTime.day'>{{downTime.day}} {{i18n['天']}}</text>
				{{downTime.hours}}:{{downTime.minutes}}:{{downTime.seconds}}
			</view>
		</view>
		<!-- 订单金额支付时间 end -->
		<!-- 支付方式 start -->
		<view class="bg-white margin-top-sm padding-lr padding-bottom-48">
			<view class="padding-tb text-666 fu-fs28 solid-bottom">{{i18n['选择支付方式']}}</view>
			<view class="flex align-center margin-top-48" v-for="(item, index) in payWaysList" :key="index" @click="changePayType(item.pay_type)">
        <view class="flex align-center flex-sub" style="min-width: 1px;">
          <image class="fu-block-56 margin-right-sm" :src="imgIcon[item.pay_type]"></image>
          <view class="text-333 fu-fs32">
            {{item.name}}
            <text class="text-prices fu-fs24" v-if="item.pay_type == 'balance'">（可用余额{{user_money}})</text>
          </view>
        </view>
        <view>
          <image class="fu-block-40" :src="imgBaseUrl + 'checked.png'" mode="" v-if="payType == item.pay_type"></image>
          <image class="fu-block-40" :src="imgBaseUrl + 'unchecked.png'" mode="" v-else></image>
        </view>
      </view>
		</view>
		<!-- 确认支付按钮 -->
		<view class="bottom-btn margin-lr bg-theme text-white text-center height-88 line-height-88 fu-fs30 round" @click="submit">{{i18n['确认支付']}}</view>
		<!-- 支付密码弹窗 -->
		<fu-pay-keyboard ref="passkeyborad" :show="payShow" :money="orderInfo.payable_money" @close="payClose" @callback="paymentByBalance"></fu-pay-keyboard>

		<!-- 密码错误弹窗 start -->
    <fu-popup ref="passErr" mode="center" width="540" height="360" border-radius="16" :mask-close-able="false" v-model="isShow">
      <view class="bg-white padding-top-40 height-360 flex flex-direction justify-between">
      	<view class="text-center">
          <view class="text-bold fu-fs32 text-333">{{i18n['提示']}}</view>
          <view class="padding-lr-43 text-333 fu-fs28 margin-top-lg">
            {{errorTip || '未知错误，请重试'}}
          </view>
        </view>
        <view class="solid-top flex align-center text-center fu-fs32 text-bold">
          <view class="padding-tb flex-sub solid-right text-999" @click="forgetPassword">{{i18n['忘记密码']}}</view>
          <view class="padding-tb flex-sub text-theme" @click="again">{{i18n['重试']}}</view>
        </view>
      </view>
    </fu-popup>
		<!-- 密码错误弹窗 end -->
		<!-- 后退弹窗 start -->
		<fu-popup ref="back" mode="center" width="540" height="360" border-radius="16" :mask-close-able="false" v-model="isContinuePay">
		  <view class="bg-white padding-top-40 height-360 flex flex-direction justify-between">
		  	<view class="text-center">
		      <view class="text-bold fu-fs32 text-333">{{i18n['确认要离开收银台?']}}</view>
		      <view class="padding-lr-43 text-333 fu-fs28 margin-top-lg">
		        {{i18n['您的订单在']}}
		        <text v-if='downTime.day'>{{downTime.day}} {{i18n['天']}}</text>
		        {{downTime.hours}}:{{downTime.minutes}}:{{downTime.seconds}}
		        {{i18n['内未支付将被取消,请尽快完成支付']}}
		      </view>
		    </view>
		    <view class="solid-top flex align-center text-center fu-fs32 text-bold">
		      <view class="padding-tb flex-sub solid-right text-999" @click="handleBackReturn(1)">{{i18n['确认离开']}}</view>
		      <view class="padding-tb flex-sub text-theme" @click="handleBackReturn(2)">{{i18n['继续支付']}}</view>
		    </view>
		  </view>
		</fu-popup>
		<!-- 后退弹窗 end -->
    <!-- 断网检测 -->
    <fu-notwork></fu-notwork>
	</view>
</template>

<script>
	// @see 密码支付组件
	import fuPayKeyboard from '../../components/fu-pay-keyboard/fu-pay-keyboard.vue';
  import minCountdown from '@/pages/order/components/min-countdown/min-countdown.vue'
	export default {
		components: {
			fuPayKeyboard,
      minCountdown
		},
		data() {
			return {
				imgIcon: { // {Obejct} 支付方式图标
					balance: 'https://oss.tiantianhuoke.com/images/168371455948373.png', // {String} 余额支付
					wxpay: 'https://zhongben-crm.oss-cn-zhangjiakou.aliyuncs.com/uploads/images/20220526/1d066923b9b33614a9df47ea787e5af9.png', // {String} 支付宝
					alipay: 'https://zhongben-crm.oss-cn-zhangjiakou.aliyuncs.com/uploads/images/20221201/33830ae4892cd61a91208d43cbc103d3.png', // {String} 微信
				},
				isContinuePay: false,
				payWaysList: [], // {Array.<Object>} 支付方式列表
				cancel_time: 0, // {Number} 支付时间
				goods_is_sale: 1, // {Number} 在支付时，判断该订单下面的商品是否已经下架 0下架 1正常
				payType: 'wxpay', // {String} 支付方式
				orderInfo: {}, // {Object} 订单信息
				order_sn: '', // {Number} 订单号
				order_type: 3, // {Number} 订单类型
				payShow: false, // {Boolean} 支付密码弹窗是否显示
				loading: false, // {Boolean} 按钮状态
				isShow: false, // {Boolean} 忘记密码
				user_money: '', // 用户余额
				itemIndex: '', // 订单列表索引
				errorTip:'', //支付失败提示
				isok:false,
				downTime: { // {Object} 支付剩余时间
					day: 0, // 天
					hours: 0, // {Number} 小时
					minutes: 0, // {Number} 分钟
					seconds: 0, // {Number} 秒钟
				},
			};
		},
		computed: {
			_time() {
				return `${Number(this.downTime.day) ? this.downTime.day + this.i18n['天'] : '' }${Number(this.downTime.hours) ? this.downTime.hours + this.i18n['时']:''}${Number(this.downTime.minutes) ? this.downTime.minutes+this.i18n['分']:''}${Number(this.downTime.seconds) ? this.downTime.seconds +this.i18n['秒']:''}`;
				// return this.downTime.day + '天' + this.downTime.hours + ':' + this.downTime.minutes + ':' + this.downTime.seconds;
			},
		},
		/**
		 * @function
		 * @description 页面加载生命周期函数
		 * @param {Object} options - 传递过来的订单参数
		 */
		async onLoad(options) {
			const { order_sn, order_type, itemIndex } = options;
			this.order_sn = order_sn;
			this.order_type = order_type;
			if (itemIndex) this.itemIndex = itemIndex;
			await this.getOrderDetail();
			await this.getMyMoney();
			this.getPayWaysList();
			this.setNavigationBarTitle(this.i18n['立即支付']);
		},
		onShow() {
			this.isShow = false;
			this.payClose();
			this.getWxpayQuery();
		},
		/**
		 * @function
		 * @description 监听页面返回
		 * @param {Object} e - {from:backbutton、 navigateBack}
		 *  backbutton 表示来源是左上角返回按钮或 android 返回键；
		 *  navigateBack表示来源是 uni.navigateBack
		 */
		onBackPress(e) {
			if (e.from == 'backbutton') {
				this.isContinuePay = true
				return true;
			} else {
				return false;
			}
		},
		methods: {
			//订单支付状态查询
			getWxpayQuery() {
			  return new Promise(resolve => {
			  	this.$api.get(global.apiUrls.getWxpayQuery, {
					order_sn: this.order_sn
				}).then(res => {
			      if (res.data.code == 1) {
			        if(res.data.data.status == 2){
						this.paySuccess(this.order_sn);
					}
					if(res.data.data.status == 3){
						this.$message.info('支付失败请重试');
					}
			        resolve()
			      }
			    })
			    .catch(err => {});
			  })
			},
      // 倒计时结束的回调
      timeOut() {
        setTimeout(()=>{
			uni.navigateBack();
		}, 800)
      },
	  initDownTime() {
	  	if (this.timer) {
	  		clearInterval(this.timer);
	  	}
	    let endTime = this.cancel_time;
	  	this.timer = setInterval(() => {
	  		// let nowTime = new Date().getTime();
	  		// let timeleft = endTime - nowTime;
			endTime--
	  		if (endTime > 0) {
	  			let hours = parseInt((endTime / (60 * 60)) % 24);
	  			let minutes = parseInt((endTime / 60) % 60);
	  			let seconds = parseInt(endTime % 60);
	  			let day = parseInt(endTime / 60 / 60 / 24); //计算剩余的天数
	  			this.downTime.day = day
	  			this.downTime.hours = hours < 10 ? '0' + hours : hours;
	  			this.downTime.minutes = minutes < 10 ? '0' + minutes : minutes;
	  			this.downTime.seconds = seconds < 10 ? '0' + seconds : seconds;
	  		} else {
	  			clearInterval(this.timer);
	  			// this.navToOrderDetail()
	  			// uni.navigateBack();
	  			this.timer = null;
				this.timeOut2();
	  		}
	  	}, 1000);
	  },
	  timeOut2(){
		  this.$api
		  	.post(global.apiUrls.postCancelOrderAuto, {
		  		order_sn: this.order_sn
		  	})
		  	.then(res => {
		  		let data = res.data;
		  		uni.hideLoading();
		  		this.$message.info(data.msg);
		  		if (data.code == 1) {
		  			// 更新列表页数据
		  			uni.$emit('onPageUpdata2');
					setTimeout(()=>{
						uni.navigateBack();
					}, 800)
		  		}
		  	});
	  },
      /**
       * @function
       * @description 获取订单详情
       */
      getOrderDetail() {
        return new Promise(resolve => {
        	this.$api.get(global.apiUrls.getOrderDetail, {
            order_sn: this.order_sn,
            order_type: this.order_type
          }).then(res => {
            if (res.data.code == 1) {
              this.orderInfo = res.data.data;
              this.goods_is_sale = res.data.data.goods_is_sale;
              this.cancel_time = res.data.data.cancel_time;
			  this.initDownTime();
              resolve()
            }
          })
          .catch(err => {});
        })
      },
      // 
      getMyMoney() {
        return new Promise(resolve => {
        	this.$api.get(global.apiUrls.getMyMoney).then(res => {
            if (res.data.code == 1) {
              this.user_money = res.data.data.user_money;
              resolve()
            }
          })
          .catch(err => {});
        })
      },
      /**
       * @function
       * @description 获取支付方式列表
       */
      getPayWaysList() {
      	let showKid = 'balance'
				// #ifdef APP-PLUS || H5
				// 上架隐藏
					this.$api.post(global.apiUrls.hiddenInterface,{code: 'is_show'}).then(res=>{
						if(res.data.data == 1){
							this.payType = "alipay"
							this.payWaysList = [
								{
									name: '支付宝',
									pay_type: "alipay"
								}
							]
						}else{
							this.payType = "wxpay"
							this.payWaysList = [
									{
										name: '微信支付',
										pay_type: "wxpay"
									},
									{
										name: '支付宝',
										pay_type: "alipay"
									}
							]
						}
					})
				// #endif
      	// #ifdef MP-WEIXIN
      	this.$api.post(global.apiUrls.postPayWaysList).then(res => {
      		if (res.data.code == 1) {
      			this.payWaysList = res.data.data;
      			
      			
      	let user_money = Number(this.user_money);
      	let payable_money = Number(this.orderInfo.payable_money);
      			if (user_money && user_money < payable_money) {
      				showKid = 'balance';
      	this.payType = 'wxpay';
      			} else {
      	  showKid = 'mix';
      	}
      			this.payWaysList = this.payWaysList.filter((item, index) => {
      			return item.pay_type !== showKid
      	})
      		}
      	}).catch(err => {
      		this.loading = false;
      	})
      	// #endif
			  },
			handleBackReturn(value) {
				this.isContinuePay = false
				if (value == 1) {
					uni.navigateBack();
				}
			},
			/**
			 * @event 密码输入错误点击重试
			 * @description 点击重试按钮
			 */
			again() {
				this.isShow = false;
				this.loading = true;
				this.callPay();
			},
			/**
			 * @event 点击忘记密码
			 * @description 点击忘记密码
			 */
			forgetPassword() {
				this.$urouter.navigateTo({
					url: "/pages/index/setting/modify-password-verify-phone/index",
					params: {
						type: 1
					}
				})
			},
			/**
			 * @event
			 * @description 关闭支付密码输入框
			 */
			payClose() {
				this.payShow = false;
			},
			/**
			 * @event
			 * @description 选择支付方式
			 * @param {String} type - 支付方式
			 * @returns {Boolean}
			 */
			changePayType(type) {
				this.payType = type;
			},
			/**
			 * @event
			 * @description 确认支付
			 * @returns {Boolean}
			 */
			submit() {
				if (this.goods_is_sale == 0) {
					this.$message.info(this.i18n['该订单下包含有已下架商品，请重新下单']);
					setTimeout(function() {
						uni.navigateBack({})
					}, 1000)
					return
				}
				// 防止二次点击
				if (this.loading) return;
				this.loading = true;
				this.callPay();
			},
			/**
			 * @function
			 * @description 判断调用哪种支付方式
			 */
			callPay() {
				if (this.payType == 'wxpay') {
					this.paymentByWxpay(this.order_sn);
				} else if (this.payType == 'alipay') {
					this.paymentByAlipay(this.order_sn);
				} else if (this.payType == 'mix') {
					this.paymentByMix(this.order_sn);
				} else {
					this.paymentByBalanceIsSetPass();
				}
			},
			/**
			 * @function
			 * @description 余额支付判断是否设置了支付密码
			 */
			paymentByBalanceIsSetPass() {
				this.$api.post(global.apiUrls.isSetPay, {
					pay_money: this.orderInfo.payable_money
				}).then(res => {
					if (res.data.code == 1) {
						if (res.data.data.falg == 1) {
							setTimeout(()=>{
								this.loading = false;
							},3000)
							this.payShow = true;
						} else {
							this.$message.info(res.data.msg);
							setTimeout(() => {
								this.loading = false;
								this.$urouter.navigateTo({
									url: '/pages/index/setting/change-pay-password/index'
								});
							}, 800);
						}
					} else {
						setTimeout(()=>{
							this.loading = false;
						},3000)
						this.$message.info(res.data.msg);
					}
				}).catch(err => {
					setTimeout(()=>{
						this.loading = false;
					},3000)
				})
			},
			/**
			 * @function
			 * @description 余额支付
			 * @param {String} pass - 用户输入的支付密码
			 */
			paymentByBalance(pass) {
				let that = this
				let query = {
					order_sn: this.order_sn
				}
				if (pass) {
					query.pay_password = pass
				} else {
					query.type = 1
				}
				this.$api.post(global.apiUrls.balancepayOrder, query).then(res => {
					if (res.data.code == 1) {
						uni.hideLoading();
						// this.$message.info('支付成功');
						if (this.$refs.passkeyborad) {
							this.$refs.passkeyborad.close();
							this.$refs.passkeyborad.close();
						}
						if (this.$refs.payfingerprint) {
							this.$refs.payfingerprint.close();
						}
						this.paySuccess(this.order_sn);
					} else if (res.data.code == 2) {
						this.$message.info(res.data.msg);
						if (this.$refs.passkeyborad) {
							this.$refs.passkeyborad.clear();
							this.$refs.passkeyborad.close();
						}
						if (this.$refs.payfingerprint) {
							this.$refs.payfingerprint.close();
						}
						setTimeout(function() {
							that.$urouter.switchTab('/pages/tab/home/shopindex/index');
						}, 1500)

					} else {
						// this.$message.info(res.data.msg);
						if (this.$refs.passkeyborad) {
							this.$refs.passkeyborad.clear();
							this.$refs.passkeyborad.close();
						}
						if (this.$refs.payfingerprint) {
							this.$refs.payfingerprint.close();
						}
						this.errorTip = res.data.msg;
						this.isShow = true;
					}
				})
			},
			/**
			 * @function
			 * @description 微信支付
			 * @param {Object} sn - 订单号
			 */
			paymentByWxpay(sn) {
				this.$api.post(global.apiUrls.wxpayOrder, {
					order_sn: sn,
					// #ifdef APP-PLUS
					wxpaytype: 'apppay',
					// #endif
					// #ifdef MP-WEIXIN
					wxpaytype: 'minipay',
					// #endif
				}).then(res => {
					setTimeout(()=>{
						this.loading = false;
					},3000)
					if (res.data.code == 1) {
						let data = res.data.data;
						
						

						
						uni.requestPayment({
							provider: 'wxpay',
							// #ifdef MP-WEIXIN
							timeStamp: data.timeStamp,
							nonceStr: data.nonceStr,
							package: data.package,
							signType: data.signType,
							paySign: data.paySign,
							// #endif
							// #ifdef APP-PLUS
							orderInfo: data,
							// #endif
							success: (e) => {
								console.log(e, 'eeeeeee')
								if (e.errMsg == 'requestPayment:ok') {
									this.paySuccess(sn);
								}
							},
							fail: (e) => {
								// #ifdef APP-PLUS
								let failMsg = 'requestPayment:fail canceled';
								// #endif
								// #ifndef APP-PLUS
								let failMsg = 'requestPayment:fail cancel';
								// #endif
								if (e.errMsg == failMsg) {
									this.$message.info(this.i18n['取消支付']);
								} else {
									this.$message.info(this.i18n["支付失败,请稍后重试"]);
									// this.$message.info("支付失败,原因为: " + e.errMsg);
								}
							},
							complete: () => {
								this.loading = false;
							}
						});
					} else {
						setTimeout(()=>{
							this.loading = false;
						},3000)
						this.$message.info(this.i18n["订单无效，支付失败!"]);
					}
				}).catch(err => {
					setTimeout(()=>{
						this.loading = false;
					},3000)
				})
			},
			/**
			 * @function
			 * @description 支付宝支付
			 * @param {Object} sn - 订单号
			 */
			// #ifndef MP-WEIXIN
			paymentByAlipay(sn) {
				this.$api.post(global.apiUrls.alipayOrder, {
					order_sn: sn,
				}).then(res => {
					if (res.data.code == 1) {
						uni.requestPayment({
							provider: 'alipay',
							orderInfo: res.data.data,
							success: (e) => {
								if (e.errMsg == 'requestPayment:ok') {
									this.paySuccess(sn);
								}
							},
							fail: (e) => {
								if (e.errMsg == 'requestPayment:fail canceled') {
									this.$message.info(this.i18n['取消支付']);
								} else {
									// this.$message.info("支付失败,原因为: " + e.errMsg);
									this.$message.info(this.i18n["支付失败,请稍后重试"]);
								}
							},
							complete: () => {
								setTimeout(()=>{
									this.loading = false;
								},3000)
							}
						})
					} else {
						setTimeout(()=>{
							this.loading = false;
						},3000)
						this.$message.info(this.i18n["订单无效，支付失败"]);
					}
				}).catch(err => {
					setTimeout(()=>{
						this.loading = false;
					},3000)
				})
			},
			// #endif
			/**
			 * @function
			 * @description 混合支付
			 * @param {Object} sn - 订单号
			 */
			paymentByMix(sn) {
				this.$api.post(global.apiUrls.mixinpayOrder, {
					order_sn: sn,
					// #ifdef APP-PLUS
					ismini: 0,
					// #endif
					// #ifdef MP-WEIXIN
					ismini: 1,
					// #endif
					balance: this.user_money,
				}).then(res => {
					if (res.data.code == 1) {
						uni.requestPayment({
							provider: 'wxpay',
							// #ifdef MP-WEIXIN
							timeStamp: res.data.data.timeStamp,
							nonceStr: res.data.data.nonceStr,
							package: res.data.data.package,
							signType: res.data.data.signType,
							paySign: res.data.data.paySign,
							// #endif
							// #ifdef APP-PLUS
							orderInfo: res.data.data,
							// #endif
							success: (e) => {
								uni.hideLoading();
								if (e.errMsg == 'requestPayment:ok') {
									this.paySuccess(sn);
								}
							},
							fail: (e) => {
								uni.hideLoading();
								if (e.errMsg == 'requestPayment:fail canceled') {
									this.$message.info(this.i18n['取消支付']);
								} else {
									this.$message.info(this.i18n["支付失败,原因为: "] + e.errMsg);
								}
							},
							complete: () => {
								setTimeout(()=>{
									this.loading = false;
								},3000)
							}
						});
					} else {
						setTimeout(()=>{
							this.loading = false;
						},3000)
						this.$message.info(res.data.msg);
					}
				}).catch(err => {
					setTimeout(()=>{
						this.loading = false;
					},3000)
				})
			},
			/**
			 * @function
			 * @description 支付成功
			 * @param {Object} sn - 支付成功
			 */
			paySuccess(sn) {
				uni.$emit('onPageUpdata', {
					type: 8,
					index: this.itemIndex,
				})
				if (this.order_type == 12) {
					uni.redirectTo({
						url: '/pages/integral/integralgoods/exchange-success/index',
						order_sn: sn,
					})
				} else {
					this.$urouter.redirectTo({
						url: '/pages/order/order-process/pay-success/index',
						params: {
							order_sn: sn,
							order_type: this.order_type,
							pay_type: this.payType
						}
					})
				}
			},
		},
	}
</script>

<style lang='scss' scoped>
	.bottom-btn {
		position: fixed;
    left: 0;
    right: 0;
		bottom: 40rpx;
		bottom: calc(40rpx + constant(safe-area-inset-bottom));
		bottom: calc(40rpx + env(safe-area-inset-bottom));
	}
</style>
